package io.renren.modules.basedata.service.impl;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.ETCCommHelper;
import cn.com.taiji.sdk.model.comm.protocol.sdts.user.UserUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.sdts.user.UserUploadResponse;
import io.renren.common.utils.DateUtil;
import io.renren.common.utils.EmptyUtil;
import io.renren.modules.basedata.dao.UserUpDao;
import io.renren.modules.basedata.entity.Tbl_user;
import io.renren.modules.basedata.service.UserUpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class UserUpServiceImpl implements UserUpService {
    private static final Logger log = LoggerFactory.getLogger(UserUpServiceImpl.class);

    @Autowired
    private UserUpDao userUpDao;
    @Override
    public String userUpload() throws Exception {
        log.info("开始获取客户信息！");
        int operResult = 0;
        List<Tbl_user> list = getuserList();//获取客户信息
        Tbl_user user = null;
        String fileName="";
        if(list!=null&&list.size()>0){
            for(int i=0;i<list.size();i++){
                user = list.get(i);
                //客户信息上传及变更接口
                UserUploadRequest request = new UserUploadRequest();
                if(user.getUsertype()==2){//单位用户
                    if(EmptyUtil.isEmpty(user.getDepartment())){
                        request.setDepartment("本部");//单位用户必填,
                    }else{
                        try{
                            request.setDepartment(user.getDepartment().trim());//单位用户必填,
                        }catch(Exception e){
                            request.setDepartment("本部");//单位用户必填,
                            log.info("上传用户信息'"+user.getId()+"'填充'指定部门/分支机构名称Department'失败，填充默认值'本部':"+e.getMessage());
                        }
                    }
                    if(EmptyUtil.isEmpty(user.getAgentName())){
                        request.setAgentName(user.getUserName().trim());//单位用户必填,默认为用户名
                    }else{
                        try{
                            request.setAgentName(user.getAgentName().trim());//单位用户必填
                        }catch(Exception e){
                            request.setAgentName(user.getUserName().trim());
                            log.info("上传用户信息'"+user.getId()+"'填充'指定经办人姓名AgentName'失败，填充默认值'"+user.getUserName().trim()+"':"+e.getMessage());
                        }
                    }
                    if(EmptyUtil.isEmpty(user.getAgentIdType())){
                        request.setAgentIdType(199);//缺省值
                    }else{
                        try{
                            request.setAgentIdType(Integer.parseInt(user.getAgentIdType().trim()));//单位用户必填
                        }catch(Exception e){
                            request.setAgentIdType(199);//单位用户必填
                            log.info("上传用户信息'"+user.getId()+"'填充'指定经办人证件类型AgentIdType'失败，填充默认值'199':"+e.getMessage());
                        }
                    }
                    if(EmptyUtil.isEmpty(user.getAgentIdNum())){
                        request.setAgentIdNum("1234567890");//单位用户必填,默认为用户证件号
                    }else {
                        try{
                            request.setAgentIdNum(user.getAgentIdNum().trim());//单位用户必填
                        }catch(Exception e){
                            request.setAgentIdNum("1234567890");
                            log.info("上传用户信息'"+user.getId()+"'填充'指定经办人证件号AgentIdNum'失败，填充默认值'1234567890':"+e.getMessage());
                        }
                    }
                }
                if(EmptyUtil.isNotEmpty(user.getBank())){
                    try {
                        request.setBank(user.getBank().trim());
                    } catch (Exception e) {
                        log.info("上传用户信息'"+user.getId()+"'填充'单位开户行Bank'失败:"+e.getMessage());
                    }
                }
                if(EmptyUtil.isNotEmpty(user.getBankAddr())){
                    try {
                        request.setBankAddr(user.getBankAddr().trim());
                    } catch (Exception e) {
                        log.info("上传用户信息'"+user.getId()+"'填充'单位开户行地址BankAddr'失败:"+e.getMessage());
                    }
                }
                if(EmptyUtil.isNotEmpty(user.getBankAccount())){
                    try {
                        request.setBankAccount(user.getBankAccount().trim());
                    } catch (Exception e) {
                        log.info("上传用户信息'"+user.getId()+"'填充'单位开户行账号BankAccount'失败:"+e.getMessage());
                    }
                }
                if(EmptyUtil.isNotEmpty(user.getTaxpayerCode())){
                    try {
                        request.setTaxpayerCode(user.getTaxpayerCode().trim());
                    } catch (Exception e) {
                        log.info("上传用户信息'"+user.getId()+"'填充'单位纳税人识别号TaxpayerCode'失败:"+e.getMessage());
                    }
                }
                request.setRegisteredTime(DateUtil.formatDateTimes(user.getRegisteredTime()));//必填
                request.setUserType(user.getUsertype());//必填1-个人2-单位
                request.setUserName(user.getUserName().trim());//必填
                request.setUserIdType(user.getUserIdType());//必填,个人证件缺省值199,单位证件缺省值299
                request.setUserIdNum(user.getUserIdNum().trim());//必填
                try {
                    request.setAddress(user.getAddress().trim());//必填
                } catch (Exception e) {
                    request.setAddress("默认地址");
                    log.info("上传用户信息'"+user.getId()+"'填充'开户人地址Address'失败，填充默认值'默认地址':"+e.getMessage());
                }
                try {
                    request.setTel(user.getTel().trim());//必填
                } catch (Exception e) {
                    request.setTel("99999999999");//必填
                    log.info("上传用户信息'"+user.getId()+"'填充'开户人/指定经办人电号码Tel'失败，填充默认值'99999999999':"+e.getMessage());
                }
                request.setRegisteredType(user.getRegisteredType());//必填,1-线上2-线下
                request.setChannelId(user.getChannelId().trim());//服务网点,必填
                request.setId(user.getId());//必填
                request.setOperation(user.getFlag());//必填
                request.setStatus(user.getStatus());//必填
                request.setStatusChangeTime(DateUtil.formatDateTimes(user.getStatusChangeTime()));
                //获取发送文件名
                fileName = ETCCommHelper.getFileName(request,"65");
                //生成就json文件
//				CreateFileUtil.createJsonFile(request.toJsonStr(), "",fileName);
                try{
                    //指定响应的协议模型,调用upload发送数据
                    UserUploadResponse response = ETCCommHelper.sdtsUpload(fileName, request, UserUploadResponse.class);
                    log.info("上传客户信息成功,服务器返回:"+response.toJson());
                    if(response!=null&&response.getInfo().equals("成功！")){

                        //上传成功,更新客户信息表状态
                        if(request.getOperation()!=3){//不是删除操作,更新该条数据
                            if(userUpDao.updateUploadUserflag(user.getId())==1){//操作成功
                                log.info("更新客户信息数据成功");
                                operResult ++;
                            }else{//操作失败
                                log.info("更新客户信息数据失败");
                            }
                        }else{//是删除操作,删除该条记录

                            if(userUpDao.deleteUploadUser(user.getId())==1){//操作成功
                                log.info("删除客户信息数据成功");
                                operResult ++;
                            }else{//操作失败
                                log.info("删除客户信息数据失败");
                            }
                        }


                    }else{
                        log.info("上传客户信息失败,失败信息:"+response.getInfo());

                        userUpDao.updateUploadUserflagError(user.getId());
                    }

                }catch(IOException e){
                    log.info("上传客户信息失败,失败信息:"+e.getMessage());
                    continue;

                }catch(ApiRequestException apie){
                    log.info("上传客户信息失败:"+apie.getMessage());
//					sqlMapClient.update("user_ORACLE.updateUploadUserflagError",user.getId());//不更新

                    if(apie.getErrCode()>=700&&apie.getErrCode()<=800){
                        if(apie.getErrCode()==707){//707表示数据重复上传,变更上传标志为已上传
                            userUpDao.updateUploadUserflag(user.getId());
                        }else{
                            userUpDao.updateUploadUserflagError(user.getId());
                        }
                    }
                    log.info(apie.getMessage());
                    continue;
                }

            }
            log.info("上传成功"+operResult+"条用户数据");
            return "上传客户信息结束！";
        }else{
            return "无客户信息,上传结束...";
        }

    }

    //获取客户信息
    @SuppressWarnings("unchecked")
    public List<Tbl_user> getuserList() throws IOException{
        List<Tbl_user> list;
        try{
            list = userUpDao.getUnuploadUserList();
        }catch(Exception e){
            e.printStackTrace();
            log.error("获取客户信息失败！错误信息:",e);
            throw new IOException("获取客户信息失败:"+e.getMessage());
        }
        return list;
    }
}
